package Offer.offer2019;

/**
 * 调整数组顺序，使奇数位于偶数前面
 * @author: leiwenkang02@meituan.com
 * @date: 2019/4/26
 * @time: 16:18
 */
public class Offer14 {
    public static void main(String[] args) {
        Offer14 offer14 = new Offer14();
        int[] array = {1,2,3,4,5,6,7,8,9};
        offer14.adjustArray(array);

        for (int i = 0; i < array.length; i++) {
            System.out.println(array[i]);
        }
    }
    public void adjustArray(int[] array) {
        if (array == null || array.length == 0) {
            return;
        }
        int start = 0;
        int end = array.length - 1;

        while (start < end) {
            while (start < end && isOddNum(array[start])) {
                start++;
            }
            while (start < end && !isOddNum(array[end])) {
                end--;
            }

            //交换
            if (start < end) {
                replace(array, start, end);
            }
        }
    }

    /**
     * 是否奇数
     * @return
     */
    private boolean isOddNum(int num) {
        if ((num & 1) == 1) {
            return true;
        }
        return false;
    }

    private void replace(int[] array, int i, int j) {
        int temp = array[i];
        array[i] = array[j];
        array[j] = temp;
    }
}
